from utils import log_debug, log_warning
from typing import List, Optional
from .base_dao import BaseDAO
from models.exam_record import ExamRecord


class ExamRecordDAO(BaseDAO[ExamRecord]):
    """考试记录表数据访问对象"""

    def __init__(self):
        """
        初始化ExamRecordDAO
        """
        super().__init__(ExamRecord)

    def _get_table_name(self) -> str:
        """获取表名"""
        return "exam_records"

    def _get_primary_key(self) -> str:
        """获取主键名"""
        return "id"

    def get_by_user_id(self, user_id: int) -> List[ExamRecord]:
        """
        根据用户ID获取所有考试记录
        :param user_id: 用户ID
        :return: 考试记录实体列表
        """
        sql = "SELECT * FROM exam_records WHERE user_id = ? ORDER BY exam_date DESC"
        results = self._execute_query(sql, (user_id,))
        log_debug(f"获取用户{user_id}的所有考试记录成功，共{len(results)}条记录")
        return results

    def get_by_user_and_category(self, user_id: int, category: str) -> List[ExamRecord]:
        """
        根据用户ID和分类获取考试记录
        :param user_id: 用户ID
        :param category: 考试分类
        :return: 考试记录实体列表
        """
        sql = "SELECT * FROM exam_records WHERE user_id = ? AND category = ? ORDER BY exam_date DESC"
        results = self._execute_query(sql, (user_id, category))
        log_debug(f"获取用户{user_id}分类{category}的考试记录成功，共{len(results)}条记录")
        return results

    def get_recent_exams(self, user_id: int, limit: int = 5) -> List[ExamRecord]:
        """
        获取用户最近的考试记录
        :param user_id: 用户ID
        :param limit: 获取的记录数限制，默认为5
        :return: 最近的考试记录实体列表
        """
        sql = "SELECT * FROM exam_records WHERE user_id = ? ORDER BY exam_date DESC LIMIT ?"
        results = self._execute_query(sql, (user_id, limit))
        log_debug(f"获取用户{user_id}的最近{limit}条考试记录成功")
        return results
    
    def get_by_id(self, exam_id: int) -> Optional[ExamRecord]:
        """
        根据考试ID获取考试记录
        :param exam_id: 考试ID
        :return: 考试记录实体，如果不存在返回None
        """
        sql = "SELECT * FROM exam_records WHERE id = ?"
        result = self._execute_query(sql, (exam_id,), single_result=True)
        if result:
            log_debug(f"获取考试ID为{exam_id}的考试记录成功")
        else:
            log_warning(f"未找到考试ID为{exam_id}的考试记录")
        return result